<?php

namespace app\admin\model\yungift;


use think\Db;

/**
 * 礼品 - 券码
 */
class GiftCode extends \addons\yungift\model\GiftCode
{
    // 自定义初始化
    protected static function init()
    {
        // 新增、更新券码
        GiftCode::event('after_write', function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if (! $scenario && empty($record['deleted_at'])) {
                return true;
            }
            Db::transaction(function () use ($record) {
                if (empty($record->gift_spec_id)) {
                    GiftMain::where(['id' => $record->gift_id])->lock(true)->find();  // 锁住礼品库存
                    $countLeft = GiftCode::where([
                        'gift_id'      => $record->gift_id,
                        'gift_spec_id' => 0,
                        'status'       => GiftCode::STATUS_NORMAL
                    ])->count();
                    GiftMain::update(['count_left' => $countLeft], ['id' => $record->gift_id]);
                } else {
                    GiftSpec::where(['id' => $record->gift_spec_id])->lock(true)->find();  // 锁住规格库存
                    $countLeft = GiftCode::where([
                        'gift_spec_id' => $record->gift_spec_id,
                        'status'       => GiftCode::STATUS_NORMAL
                    ])->count();
                    GiftSpec::update([
                        'count_left' => $countLeft,
                        'gift_id'    => $record->gift_id,
                        'scenario'   => 'sync'
                    ], ['id' => $record->gift_spec_id], true);
                }
            });

            return true;
        });
    }
}
